'''
#>>> @opencv 探究opencv读取图像的到的数组,(240,320,3),将其rbg转换成一维数组
#>>> @conv   将rbg三色转换成与image2Lcd.exe生成的以为C语言的一维数列
#>>> @transform 将一维数列通过udp传输给esp32
#>>> display 观察图像显示情况,修改TFTLCD_ili9341驱动程序
#>>> @key opencv与image2Lcd.exe一样采取水平扫描,opencv默认度去图像通道是BGR
'''


from socket import *
import os 
from os import path 
import struct
import time
import cv2

Path = 'E:/Learn/2.project_code/tftlcd/image/'
image_types = "jpg"
image_num = 0

# Define image width and height
image_height = 0
image_width = 0

# Rgb channel color is converted to ili9431 lcd display value
def color565(r, g, b):
    return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3


# Image saving: save the read image as a hexadecimal array,
# store it in a Python file
def image_list_save(data):
    global image_num
    line = image_width
    length = image_height*image_width*2
    if len(data) == length:
        image_num += 1
        print(image_num)
    else:
        print('数据读取错误！！！')
    txt_name = Path + 'image' + str(image_num) + '.py'
    list_name = 'Imagedata' + str(image_num) + ' = ' + '['
    file = open(txt_name, 'w')
    print(length, len(data))
    for v in range(-1, length+1):
        if v == -1:
            file.write(list_name+'\n')
        elif (v+1) % line == 0:
            file.write(data[v] + ',' + '\n')
        elif v == length:
            file.write(']')
        elif v != length-1:
            file.write(data[v] + ',')
    file.flush()
    file.close()

def image_dict_save(data):
    global image_num
    line = image_width*2
    lineh = 0
    length = image_height * image_width * 2
    if len(data) == length:
        image_num += 1
        print(image_num)
    else:
        print('数据读取错误！！！')
    txt_name = Path + 'image' + str(image_num) + '.py'
    list_name = 'Imagedata' + str(image_num) + ' = ' + '{'
    file = open(txt_name, 'w')
    print(length, len(data))
    for v in range(-1, length + 1):
        if v == -1:
            file.write(list_name + '\n')
            file.write('0' + ':' + '[')
        elif (v + 1) % line == 0:
            lineh += 1
            file.write(data[v] + ']' + ',' + '\n')
            if lineh < image_height:
                file.write(str(lineh) + ':' + '[')
        elif v == length:
            file.write('}')
        elif v != length - 1:
            file.write(data[v] + ',')
    file.flush()
    file.close()


# Three-dimensional sequence is converted to one-dimensional sequence
# and it is 8 bytes per bit
def seque_conv(clor565):
    data_hex = []
    # print(clor565)
    for i in range(len(clor565)):
        hex_high = (clor565[i] >> 8) & 0xff
        hex_low = (clor565[i] & 0xff)
        data_hex.append(hex(hex_high))
        data_hex.append(hex(hex_low))

    if len(data_hex) == (image_height*image_width*2):
        # image_list_save(data_hex)
        image_dict_save(data_hex)
        return data_hex


# Get the picture color channel value
def color_rgb565(image):
    image_seque = []  # Set an empty one-dimensional sequence
    if image_width >= image_height:
        for i in range(image_height):
            for j in range(image_width):
                b, g, r = image[i][j]
                image_seque.extend([color565(r, g, b)])
    else:
        for j in range(image_height):
             for i in range(image_width):
                b, g, r = image[j][i]
                image_seque.extend([color565(r, g, b)])

    if len(image_seque) == image_height * image_width:
        return image_seque
        # seque_conv(image_seque)

    cv2.imshow('image', image)
    cv2.waitKey()


# Find all the specified pictures in the specified folder and read the path
def search_sameSuffix_file(dirPath):
    # Modify values for global variables
    global image_height, image_width

    dirs = os.listdir(dirPath)
    for currentFile in dirs:
        fullPath = dirPath + currentFile
        # if os.path.isdir(fullPath):
        #     search_sameSuffix_file(fullPath)
        if currentFile.split('.')[-1] == image_types:
            # Define image width and height
            image_height = (cv2.imread(fullPath)).shape[0]
            image_width = (cv2.imread(fullPath)).shape[1]
            color_rgb565(cv2.imread(fullPath))


# Get a picture data directly
def direct_read_image(path):
    global image_height, image_width
    image_height = (cv2.imread(path)).shape[0]
    image_width = (cv2.imread(path)).shape[1]
    image = cv2.imread(path)

    if image is not None:
        return image, image_width, image_height


# if __name__ == '__main__':
# #	color_rgb565()
# 	search_sameSuffix_file(Path)
